package com.base.controller;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RequestMapping("admin/common")
@RestController
@Slf4j
@Api(tags = "通用接口")
public class CommonController {
       @Autowired
       AliOssUtil aliOssUtil;

       @PostMapping("upload")
       @ApiOperation("上传图片")
       public Result<String>  upLoad(MultipartFile file) {
             try {
                 log.info("文件上传{}", file);
                 //原始文件名
                 String originalFileName = file.getOriginalFilename();
                 //获取文件类型
                 String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
                 //构造新的文件名 uuid
                 String objectName = UUID.randomUUID().toString() + extension;
                 //生成请求路径
                 String fileName = aliOssUtil.upload(file.getBytes(), objectName);
                 return Result.success(fileName);
             }
             catch (IOException exception){
                  log.error("文件上传失败:{}", exception);
             }
             return Result.error(MessageConstant.UPLOAD_FAILED);
       }
}
